const jwt = require('jsonwebtoken');
const appConfig = require('../configs/appConfig');
const apiStatus = require('../apiStatus');

const jwtTokenAuth = function() {
    const _authConfig = function (app) {
        app.jwtAuthorize = async(ctx,next) => {
            const jwtToken = ctx.request.header['authorization'].replace(/bearer /ig,'');
            console.log(jwtToken);
            if (!jwtToken || !jwtToken.length){
                ctx.body = {apiStatus:apiStatus.jwtTokenRequired};
                return;
            }
            try{
                var payload = jwt.verify(jwtToken, appConfig.jwt.secret);
                console.log("payload:");
                console.log(payload);
                ctx.user = payload;
                await next();
            }catch(err){
                console.log(err);
                ctx.body = {apiStatus: apiStatus.jwtTokenInvalid};
                return;
            }
        }
    }

    return {
        authConfig: _authConfig
    }
}();

module.exports = jwtTokenAuth;
